﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Diagnostics;

namespace Master
{
    /**
     * Spawnpoint can be used to mark a specific lane as a 'spawnlane' on which you can easily add new cars.
     * Just create a spawnpoint, locate it on top of a lane somewhere and pass the spawnpoint to the carmanager.addCar-method.
     * A new car will be created just before the beginning of the above mentioned lane.
     * The orientation of the lane will be used as orientation for the newly created car.
     * 
     * @Version 0.2
     * */
    public class SpawnPoint : Control
    {
        /**
         * Method to retrieve the exact location new cars should spawn on. 
         * This will generate a centered location just before the beginning of the relevant lane.
         * (Newly spawned cars will have to be centered on this point)
         * */
        public Point getPoint(Car car)
        {
            Lane lane = getLane();
            Point lanePoint = Toolkit.getPointRelativeToMap(lane);
            Point point = new Point();
            switch (lane.Orientation)
            {
                case 0:
                    point.X = ((lanePoint.X * 2) + lane.ActualWidth) / 2;
                    point.Y = lanePoint.Y + lane.ActualHeight + car.getTrueBounds().Height;
                    break;
                case 90:
                    point.X = lanePoint.X - car.getTrueBounds().Width;
                    point.Y = ((lanePoint.Y * 2) + lane.ActualHeight) / 2;
                    break;
                case 180:
                    point.X = ((lanePoint.X * 2) + lane.ActualWidth) / 2;
                    point.Y = lanePoint.Y - car.getTrueBounds().Height;
                    break;
                case 270:
                    point.X = lanePoint.X + lane.ActualWidth + car.getTrueBounds().Width;
                    point.Y = ((lanePoint.Y * 2) + lane.ActualHeight) / 2;
                    break;
            }
            return point;
        }

        /**
         * Method to retrieve the lane associated with this spawnpoint.
         * */
        public Lane getLane()
        {
            Lane lane = Map.INSTANCE.getLaneAt(myPoint());
            if (lane == null)
                throw new InvalidOperationException("Spawnpoint not located on lane");
            return lane;
        }

        private Point myPoint()
        {
            return new Point(Map.GetLeft(this), Map.GetTop(this));
        }
    }
}
